package com.hw.paltfrom.service.supervisor;

import java.sql.Timestamp;
import java.util.*;

import com.baomidou.mybatisplus.mapper.Wrapper;
import com.hw.paltfrom.mapper.*;
import com.hw.paltfrom.pojo.*;
import com.hw.paltfrom.service.doncutor.BaseWorkflowService;
import com.hw.paltfrom.service.doncutor.CommandWorkflowService;
import com.hw.paltfrom.utils.PageUtils;
import com.hw.paltfrom.vo.FileInfo;
import com.hw.paltfrom.vo.StepInfoVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hw.paltfrom.exception.HWSystemException;
import com.hw.paltfrom.rescode.HWSystemCode;
import com.hw.paltfrom.utils.RandomNumberUtil;
import com.hw.paltfrom.utils.ResponeResultUtil;
import com.hw.paltfrom.vo.SupervisionVo;

@Service
public class SupervisorManagerServer {

    @Autowired
    private HwSupervisionMapper supervisionMapper;

    @Autowired
    private HwBaseUserMapper baseUserMapper;

    @Autowired
    private BaseWorkflowService baseWorkflowService;

    @Autowired
    private CommandWorkflowService commandWorkflowService;

    @Autowired
    private HwBaseAnnexesfileMapper hwBaseAnnexesfileMapper;

    @Autowired
    HwBaseOverrunstationMapper overrunstationMapper;

    @Autowired
    HwBaseCountycoreMapper countycoreMapper;

    // 查询
    public Map<String, Object> query(SupervisionVo vo) {

        Integer pageNum = vo.getPageNum();
        Integer pageSize = vo.getPageSize();

        String f_CurrentStep = vo.getfCurrentstep();
        String f_Title = vo.getfTitle();


        EntityWrapper<HwSupervision> entityWrapper = new EntityWrapper<HwSupervision>();

        // 完结f_CurrentStep=04 未完结不传f_CurrentStep
        if (StringUtils.isNotBlank(f_CurrentStep)) {
            entityWrapper.eq("F_CurrentStep", f_CurrentStep);
        } else {
            entityWrapper.ne("F_CurrentStep", "04");
        }

        if (StringUtils.isNotBlank(f_Title)) {
            entityWrapper.like("F_Title", f_Title);
        }
        entityWrapper.orderBy("F_FromTime", false);
        List<HwSupervision> selectList = supervisionMapper.selectList(entityWrapper);
        List<SupervisionVo> supervisionVoList = new LinkedList<>();
        for (HwSupervision hwSupervision : selectList) {
            SupervisionVo supervisionVo = new SupervisionVo();
            supervisionVo.setfSpvid(hwSupervision.getfSpvid());
            supervisionVo.setfFromobjectid(hwSupervision
            .getfFromobjectid());
            supervisionVo.setfFromtype(hwSupervision.getfFromtype());
            supervisionVo.setfFromdepcode(hwSupervision.getfFromdepcode());
            supervisionVo.setfFromuserid(hwSupervision.getfFromuserid());
            supervisionVo.setfFromusername(hwSupervision.getfFromusername());
            supervisionVo.setfFromtime(hwSupervision.getfFromtime());
            supervisionVo.setfTitle(hwSupervision.getfTitle());
            supervisionVo.setfFromsrc(hwSupervision.getfFromsrc());
            supervisionVo.setfSpvcontent(hwSupervision.getfSpvcontent());
            supervisionVo.setfCurrentstep(hwSupervision.getfCurrentstep());
            supervisionVo.setfBacktype(hwSupervision.getfBacktype());
            supervisionVo.setfBackdepcode(hwSupervision.getfBackdepcode());
            supervisionVo.setfBackdepname(hwSupervision.getfBackdepname());
            supervisionVo.setfBacktime(hwSupervision.getfBacktime());
            supervisionVo.setfBackuserid(hwSupervision.getfBackuserid());
            supervisionVo.setfBackusername(hwSupervision.getfBackusername());
            supervisionVo.setfBackuserphone(hwSupervision.getfBackuserphone());
            if(hwSupervision.getfBackcontent()!=null){
            	supervisionVo.setfBackcontent(hwSupervision.getfBackcontent().toString());
            }
            supervisionVo.setfBackfile(hwSupervision.getfBackfile());
            supervisionVo.setfBackassignstate(hwSupervision.getfBackassignstate());
            supervisionVo.setIsStagestate(hwSupervision.getIsStagestate());
            supervisionVo.setFlowCode("JCDD");
            supervisionVoList.add(supervisionVo);
        }
        PageUtils<SupervisionVo> pageUtils = new PageUtils<>(pageNum, pageSize);
        Object pageResult = pageUtils.getPageResult(supervisionVoList);
        return ResponeResultUtil.successNotice(HWSystemCode.SUCCESS, pageResult);

    }

    // 创建
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class, RuntimeException.class,
            HWSystemException.class})
    public Map<String, Object> create(SupervisionVo vo) {

        // 判断当前用户是不是市级用户
        String loginid = vo.getfFromuserid();
        HwBaseUser user = baseUserMapper.selectById(loginid);
        if (user.getfType() != 1) {
            return ResponeResultUtil.fail(HWSystemCode.AUTH_FAIL);
        }

        
        
        String fSpvid = RandomNumberUtil.getNumber();
        HwSupervision supervision = new HwSupervision();
        
        supervision.setfFromuserid(vo.getfAccount());
        supervision.setfFromusername(vo.getfFromusername());
        
        supervision.setfSpvid(fSpvid);
        supervision.setfFromobjectid(vo.getfFromobjectid());
        supervision.setfFromtype(vo.getfFromtype());
        supervision.setfFromdepcode(vo.getfFromdepcode());
        
        supervision.setfFromtime(new Timestamp(System.currentTimeMillis()));
        supervision.setfTitle(vo.getfTitle());
        supervision.setfFromsrc(vo.getfFromsrc());
        supervision.setfSpvcontent(vo.getfSpvcontent());
        supervision.setfBackassignstate(0);
        
        supervision.setIsStagestate(0);
        // 创建基础流程

        HwBaseWorkflow baseWorkflow = baseWorkflowService.getStartBaseWorkflow("JCDD");
        supervision.setfCurrentstep(baseWorkflow.getWorkflowNextcode());
        supervision.setfBacktype(vo.getfBacktype());
        supervision.setfBackdepcode(vo.getfBackdepcode());
        supervision.setfBackdepname(vo.getfBackdepname());
        Integer insert = supervisionMapper.insert(supervision);
        if (insert != 1) {
            return ResponeResultUtil.fail(HWSystemCode.FAIL);
        }


        // 审批流水数据
        HwCommandWorkflow hwCommandWorkflow = new HwCommandWorkflow();
        
        hwCommandWorkflow.setCommandworkflowButtonname(vo.getButtonName());
        hwCommandWorkflow.setfAccount(vo.getfAccount());
        
        
        hwCommandWorkflow.setCommandworkflowId(RandomNumberUtil.getNumber());//主键
        hwCommandWorkflow.setWorkflowModule(baseWorkflow.getWorkflowModule());
        hwCommandWorkflow.setWorkflowType(baseWorkflow.getWorkflowType());
        hwCommandWorkflow.setWorkflowCode(baseWorkflow.getWorkflowCode());
        hwCommandWorkflow.setWorkflowCodename(baseWorkflow.getWorkflowCodename());
        hwCommandWorkflow.setfFromdepcode(vo.getfFromdepcode());
        hwCommandWorkflow.setfFromdepname(vo.getfFromtype());
        hwCommandWorkflow.setCommandworkflowDatatime(new Date());
        hwCommandWorkflow.setCommandworkflowContent(vo.getfSpvcontent());
        hwCommandWorkflow.setObjectId(fSpvid);
        hwCommandWorkflow.setWorkflowNextcode(baseWorkflow.getWorkflowNextcode());
        hwCommandWorkflow.setWorkflowNextcodename(baseWorkflow.getWorkflowNextcodename());

        boolean b = commandWorkflowService.addWorkflow(hwCommandWorkflow);
        if (b == false) {
            throw new HWSystemException();
        }
        return ResponeResultUtil.success(HWSystemCode.SUCCESS);
    }

    // 详情
    public Map<String,Object> detail(String F_SpvId){
        HwSupervision hwSupervision = supervisionMapper.selectById(F_SpvId);
        return ResponeResultUtil.successNotice(HWSystemCode.SUCCESS,hwSupervision);
    }

    // 修改
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class, RuntimeException.class,
            HWSystemException.class})
    public Map<String, Object> update(SupervisionVo vo) {

        // 判断当前用户是不是市级用户
        String loginid = vo.getfFromuserid();
        HwBaseUser user = baseUserMapper.selectById(loginid);
        if (user.getfType() != 1) {
            return ResponeResultUtil.fail(HWSystemCode.AUTH_FAIL);
        }

        // 已经完结的不能修改
        HwSupervision entity = supervisionMapper.selectById(vo.getfSpvid());
        if (entity.getfCurrentstep().equals("04")) {
            return ResponeResultUtil.fail(HWSystemCode.IS_END);
        }

        EntityWrapper<HwSupervision> entityWrapper = new EntityWrapper<HwSupervision>();
        entityWrapper.eq("F_SpvId", vo.getfSpvid());

        HwSupervision supervision = new HwSupervision();
        supervision.setfSpvcontent(vo.getfSpvcontent());
        Integer update = supervisionMapper.update(supervision, entityWrapper);
        if (update != 1) {
            return ResponeResultUtil.fail(HWSystemCode.FAIL);
        }

        HwBaseWorkflow baseWorkflow = baseWorkflowService.getPresentWorkflow(entity.getfCurrentstep(), "JCDD");
        // 审批流水数据
        HwCommandWorkflow hwCommandWorkflow = new HwCommandWorkflow();
        hwCommandWorkflow.setCommandworkflowId(RandomNumberUtil.getNumber());//主键
        hwCommandWorkflow.setWorkflowModule(baseWorkflow.getWorkflowModule());
        hwCommandWorkflow.setWorkflowType(baseWorkflow.getWorkflowType());
        hwCommandWorkflow.setWorkflowCode(baseWorkflow.getWorkflowCode());
        hwCommandWorkflow.setWorkflowCodename(baseWorkflow.getWorkflowCodename());
        hwCommandWorkflow.setCommandworkflowButtonname(vo.getButtonName());
        hwCommandWorkflow.setfAccount(vo.getfAccount());
        hwCommandWorkflow.setfFromdepcode(vo.getfFromdepcode());
        hwCommandWorkflow.setfFromdepname(vo.getfFromtype());
        hwCommandWorkflow.setCommandworkflowDatatime(new Date());
        hwCommandWorkflow.setCommandworkflowContent(vo.getfSpvcontent());
        hwCommandWorkflow.setObjectId(entity.getfSpvid());
        hwCommandWorkflow.setWorkflowNextcode("99");
        hwCommandWorkflow.setWorkflowNextcodename("");

        boolean b = commandWorkflowService.addWorkflow(hwCommandWorkflow);
        if (b == false) {
            throw new HWSystemException();
        }

        return ResponeResultUtil.success(HWSystemCode.SUCCESS);
    }

    // 删除
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class, RuntimeException.class,
            HWSystemException.class})
    public Map<String, Object> delete(SupervisionVo vo) {
        // 判断当前用户是不是市级用户
        String loginid = vo.getfFromuserid();
        HwBaseUser user = baseUserMapper.selectById(loginid);
        if (user.getfType() != 1) {
            return ResponeResultUtil.fail(HWSystemCode.AUTH_FAIL);
        }

        // 已经完结的不能修改
        HwSupervision entity = supervisionMapper.selectById(vo.getfSpvid());
        if (entity.getfCurrentstep().equals("04")) {
            return ResponeResultUtil.fail(HWSystemCode.IS_END);
        }

        Integer delete = supervisionMapper.deleteById(vo.getfSpvid());
        if (delete != 1) {
            return ResponeResultUtil.fail(HWSystemCode.FAIL);
        }

        //查询当前工作流
        HwBaseWorkflow baseWorkflow = baseWorkflowService.getPresentWorkflow(entity.getfCurrentstep(), "JCDD");
        // 审批流水数据
        HwCommandWorkflow hwCommandWorkflow = new HwCommandWorkflow();
        hwCommandWorkflow.setCommandworkflowId(RandomNumberUtil.getNumber());//主键
        hwCommandWorkflow.setWorkflowModule(baseWorkflow.getWorkflowModule());
        hwCommandWorkflow.setWorkflowType(baseWorkflow.getWorkflowType());
        hwCommandWorkflow.setWorkflowCode(baseWorkflow.getWorkflowCode());
        hwCommandWorkflow.setWorkflowCodename(baseWorkflow.getWorkflowCodename());
        hwCommandWorkflow.setCommandworkflowButtonname(vo.getButtonName());
        hwCommandWorkflow.setfAccount(vo.getfAccount());
        hwCommandWorkflow.setfFromdepcode(vo.getfFromdepcode());
        hwCommandWorkflow.setfFromdepname(vo.getfFromtype());
        hwCommandWorkflow.setCommandworkflowDatatime(new Date());
        hwCommandWorkflow.setCommandworkflowContent(vo.getfSpvcontent());
        hwCommandWorkflow.setObjectId(entity.getfSpvid());
        hwCommandWorkflow.setWorkflowNextcode("99");
        hwCommandWorkflow.setWorkflowNextcodename("");

        boolean b = commandWorkflowService.addWorkflow(hwCommandWorkflow);
        if (b == false) {
            throw new HWSystemException();
        }
        return ResponeResultUtil.success(HWSystemCode.SUCCESS);
    }

    //完结审核
    @Transactional(rollbackFor = {Exception.class, RuntimeException.class, HWSystemException.class})
    public Map<String,Object> finish(StepInfoVO vo){
        //根据督导任务主键id查出督导任务表
        String taskId = vo.getTaskId();
        HwSupervision hwSupervision = supervisionMapper.selectById(taskId);

        //取出当前办理阶段判断是否不是"03"
        String currentstep = hwSupervision.getfCurrentstep();
        if (!currentstep.equals("03")){
            return ResponeResultUtil.failNotice(HWSystemCode.FAIL,"该信息不能进行完结审核处理！");
        }
        //根据workflowDoResult判断1完结,2退回,3延期
        Integer workflowDoresult = vo.getWorkflowDoresult();
        String workflowNextcode = vo.getWorkflowNextcode();

        hwSupervision.setfCurrentstep(workflowNextcode);
        hwSupervision.setIsStagestate(workflowDoresult);

        Integer update = supervisionMapper.updateById(hwSupervision);
        if (update != 1){
            throw new HWSystemException();
        }

        //插入附件表附件
        //生成folderId
        String folderId = RandomNumberUtil.getNumber();
        List<FileInfo> fileInfoList = vo.getFileInfoList();
        int i =0;
        for (FileInfo fileInfo : fileInfoList) {
            ++i;
            HwBaseAnnexesfile hwBaseAnnexesfile = new HwBaseAnnexesfile();
            hwBaseAnnexesfile.setFileId(RandomNumberUtil.getNumber());
            hwBaseAnnexesfile.setfFolderid(folderId);
            hwBaseAnnexesfile.setFileType(fileInfo.getFileType());
//				hwBaseAnnexesfile.setFileName(vo.getFileName()+String.valueOf(i));
            hwBaseAnnexesfile.setFileName("检查督导完结附件"+String.valueOf(i));
            hwBaseAnnexesfile.setFilePath(fileInfo.getFilePath());
            hwBaseAnnexesfile.setFileSize(fileInfo.getFileSize());
            hwBaseAnnexesfile.setFileMoudletype("JCDDFILE检查督导");
            hwBaseAnnexesfile.setfCreatedate(new Timestamp(System.currentTimeMillis()));
            hwBaseAnnexesfile.setfCreateusername(vo.getLoginUser());
            Integer insert = hwBaseAnnexesfileMapper.insert(hwBaseAnnexesfile);
            if (insert != 1) {
                throw new HWSystemException();
            }
        }
        //查询当前工作流
        HwBaseWorkflow baseWorkflow = baseWorkflowService.getPresentWorkflow(vo.getWorkflowCode(), "JCDD");
        // 审批流水数据
        HwCommandWorkflow hwCommandWorkflow = new HwCommandWorkflow();
        hwCommandWorkflow.setCommandworkflowId(RandomNumberUtil.getNumber());//主键
        hwCommandWorkflow.setWorkflowModule(baseWorkflow.getWorkflowModule());
        hwCommandWorkflow.setWorkflowType(baseWorkflow.getWorkflowType());
        hwCommandWorkflow.setWorkflowCode(baseWorkflow.getWorkflowCode());
        hwCommandWorkflow.setWorkflowCodename(baseWorkflow.getWorkflowCodename());
        hwCommandWorkflow.setCommandworkflowButtonname(vo.getButtonName());
        hwCommandWorkflow.setfAccount(vo.getLoginUser());
        hwCommandWorkflow.setfFromdepcode(vo.getDeptCode());
        hwCommandWorkflow.setfFromdepname(vo.getDeptName());
        hwCommandWorkflow.setCommandworkflowDatatime(new Date());
        hwCommandWorkflow.setCommandworkflowContent(vo.getContent());
        hwCommandWorkflow.setObjectId(hwSupervision.getfSpvid());
        hwCommandWorkflow.setWorkflowNextcode(vo.getWorkflowNextcode());
        hwCommandWorkflow.setWorkflowNextcodename(vo.getWorkflowNextname());
        hwCommandWorkflow.setfAnnexes(folderId);
        boolean b = commandWorkflowService.addWorkflow(hwCommandWorkflow);
        if (b == false) {
            throw new HWSystemException();
        }
        return ResponeResultUtil.success(HWSystemCode.SUCCESS);
    }

    //查询单位
    public Map<String,Object> queryDepList(String type){
        switch (type){
            case "2":
                Wrapper<HwBaseCountycore> countycoreWrapper = new EntityWrapper<>();
                countycoreWrapper.eq("F_DeleteMark",0)
                        .eq("F_EnabledMark",1).ne("F_AreaId", "1407")
                        .orderBy("F_SortCode",true);
                List<HwBaseCountycore> hwBaseCountycoreList = countycoreMapper.selectList(countycoreWrapper);
                return ResponeResultUtil.successNotice(HWSystemCode.SUCCESS,hwBaseCountycoreList);
            case "3":Wrapper<HwBaseOverrunstation> overrunstationWrapper = new EntityWrapper<>();
                overrunstationWrapper.eq("F_DeleteMark",0)
                        .eq("F_EnabledMark",1)
                        .orderBy("F_SortCode",true);
                List<HwBaseOverrunstation> hwBaseOverrunstationList = overrunstationMapper.selectList(overrunstationWrapper);
                return ResponeResultUtil.successNotice(HWSystemCode.SUCCESS,hwBaseOverrunstationList);
            default:return ResponeResultUtil.fail(HWSystemCode.DATA_NOTFOUND);
        }
    }
}
